package com.atjava.nebula.web.ssl;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * https访问工具类
 * @author kyo
 *
 */
public class HttpsClient {
	
	private final int TIMEOUT_SEC = 10000;
	
	private String encoding;
	private Map<String, String>	reqProperty = null;
	
	public static void setTrustAllHosts() {

		// Create a trust manager that does not validate certificate chains
		X509TrustManager x509TrustManager = new X509TrustManager() {

			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return new java.security.cert.X509Certificate[] {};
			}

			public void checkClientTrusted(X509Certificate[] chain,
					String authType) throws CertificateException {
			}

			public void checkServerTrusted(X509Certificate[] chain,
					String authType) throws CertificateException {
			}
		};
		TrustManager[] trustAllCerts = new TrustManager[] { x509TrustManager };
		try {
			SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(null, trustAllCerts, new java.security.SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	public HttpsClient(String encoding){
		HttpsURLConnection.setDefaultHostnameVerifier(new NoHostnameVerifier());
		this.encoding = encoding;
		this.reqProperty = new HashMap<String, String>();
		this.reqProperty.put("Content-Type", "text/xml");
	}
	
	public HttpsClient(){
		this("UTF-8");
	}
	
	public void setRequestProperty(String key,String value) {
		this.reqProperty.put(key, value);
	}
	
	public String get(String urlstr) throws IOException {
		URL url = new URL(urlstr);
		HttpsURLConnection connection = null;
		InputStream is = null;
		BufferedReader reader = null;
		String response = "";
		
		try {
			connection = (HttpsURLConnection) url.openConnection();
			setRequestProperty(connection);
			
			connection.setReadTimeout(TIMEOUT_SEC);
			connection.setDoOutput(false); // true for POST, false for GET
			connection.setDoInput(true);
			connection.setRequestMethod("GET");
			connection.setUseCaches(false);
			
			is = connection.getInputStream();
			reader = new BufferedReader(new InputStreamReader(is, this.encoding));
			String line = null;
			while ((line = reader.readLine()) != null) {
				response += line+ "\r\n";
			}
			
		} finally{
			is.close();
			reader.close();
			connection.disconnect();
		}
		
		return response;
	}
	
	public String post(String urlstr,byte data[]) throws IOException {
		URL url = new URL(urlstr);
		HttpsURLConnection connection = null;
		OutputStream os = null;
		InputStream is = null;
		BufferedReader reader = null;
		String response = "";
		
		try {
			connection = (HttpsURLConnection) url.openConnection();
			setRequestProperty(connection);
			
			connection.setReadTimeout(TIMEOUT_SEC);
			connection.setDoOutput(true); // true for POST, false for GET
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			
			os = connection.getOutputStream();
			os.write(data);

		
			
			is = connection.getInputStream();
			reader = new BufferedReader(new InputStreamReader(is, this.encoding));
			String line = null;
			while ((line = reader.readLine()) != null) {
				response += line+ "\r\n";
			}
			
		} finally{
			is.close();
			os.close();
			reader.close();
			connection.disconnect();
		}
		
		return response;
	}
	
	
	public String post(String urlstr,File file) throws IOException{
		FileInputStream fis = null;
		byte[] data = null;
		try {
			fis = new FileInputStream(file);
			data = new byte[(int) file.length()];
			fis.read(data);
		} finally {
			fis.close();
		}
		return post(urlstr, data);
		
	}
	
	public String post(String urlstr,String inputStr) throws IOException{
		byte[] data = inputStr.getBytes(this.encoding);
		return post(urlstr, data);
	}

	private void setRequestProperty(HttpsURLConnection connection){
		Iterator<String> iterator = this.reqProperty.keySet().iterator();
		while(iterator.hasNext()){
			String key = iterator.next();
			connection.setRequestProperty(key, this.reqProperty.get(key));
		}
	}
	/**
	 * method of get file media_id 
	 * @throws IOException 
	 *
	 */
	public String getFileMediaIdByPostMothod(String urlStr ,File file) throws IOException{
		URL url = new URL(urlStr);
		HttpsURLConnection connection = null;
		OutputStream os = null;
		InputStream is = null;
		BufferedReader reader = null;
		String response = "";
		
		try {
			connection = (HttpsURLConnection) url.openConnection();
			setRequestProperty(connection);
			
			connection.setReadTimeout(TIMEOUT_SEC);
			connection.setDoOutput(true); // true for POST, false for GET
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			
			// 设置请求头信息  
			connection.setRequestProperty("Connection", "Keep-Alive");  
			connection.setRequestProperty("Charset", "UTF-8");  
		  
		  
			// 设置边界  
			String BOUNDARY = "----------" + System.currentTimeMillis();  
			connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY);  
			
			StringBuilder sb = new StringBuilder();  
			sb.append("--"); // 必须多两道线  
			sb.append(BOUNDARY);  
			sb.append("\r\n");  
			sb.append("Content-Disposition: form-data;name=\"file\";filename=\""  
			+ file.getName() + "\"\r\n");  
			sb.append("Content-Type:application/octet-stream\r\n\r\n");  
			  
			    byte[] head = sb.toString().getBytes("utf-8");  
			byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线 
			
			// 获得输出流  
			os = connection.getOutputStream();
			os.write(head); 
			
			DataInputStream in = new DataInputStream(new FileInputStream(file));  
			int bytes = 0;  
			byte[] bufferOut = new byte[1024];  
			while ((bytes = in.read(bufferOut)) != -1) {  
			  os.write(bufferOut, 0, bytes);  
			};
			in.close(); 
		 
			os.write(foot);
			os.flush();
			os.close();
			
			is = connection.getInputStream();
			reader = new BufferedReader(new InputStreamReader(is, this.encoding));
			String line = null;
			while ((line = reader.readLine()) != null) {
				response += line+ "\r\n";
			}
			
		} finally{
			is.close();
			reader.close();
			connection.disconnect();
		}
		
		return response;
	}
}